package com.example.lib_apply

import android.app.Activity
import android.app.DatePickerDialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewbinding.ViewBinding
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.example.lib_apply.databinding.ActivityApplyBinding
import com.example.lib_common.mvi.BaseActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.*


@Route(path = "/apply/ApplyActivity")
class ApplyActivity : BaseActivity<ActivityApplyBinding,ApplyViewModel>(),OnItemClickListener,DatePicker.OnDateChangedListener{
    private  var allApply : ArrayList<ApplyEntity> =ArrayList()
    private  var statues_txt : ArrayList<String> =ArrayList()
    val applyAdapter= ApplyAdapter()
    override fun createVM(): ApplyViewModel {
        return ApplyViewModel()
    }

    override fun createViewBinding(): ViewBinding {
        return ActivityApplyBinding.inflate(inflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        var map=HashMap<String,Any>()
        initDate()
        map["time"]=System.currentTimeMillis().toString()
        map["userId"]=SPUtils.getInstance().getInt("uId")
        vm.requestAll(map)
        bindState()
        search()
        v.backBtn.setOnClickListener { finish() }
    }


    private fun bindState() {
        lifecycleScope.launch(Dispatchers.Main){
            repeatOnLifecycle(Lifecycle.State.STARTED){
                vm.mutableContainer.uiStateFlow.collect{
                    if (it.entity.statuesCode==200){
                        allApply= it.entity.values as ArrayList<ApplyEntity>
                        bindAdapter()
                    }
                }
            }
        }
    }

    private fun bindAdapter() {
        val  startCalendar= Calendar.getInstance()
        val  endCalendar= Calendar.getInstance()
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation=LinearLayoutManager.VERTICAL
        v.myApplyRecycler.layoutManager=layoutManager
        if (allApply.size>0){
            applyAdapter.data = allApply
        }
        v.myApplyRecycler.adapter=applyAdapter
        for (applyEntity in allApply) {
            try {
                val applyTime = applyEntity.applyTime!!.toLong()
                startCalendar.timeInMillis=applyTime
                endCalendar.timeInMillis=applyTime*1000
                val startMonth = startCalendar.get(Calendar.MONTH)
                val starDay = startCalendar.get(Calendar.DAY_OF_MONTH)
                val endMonth = endCalendar.get(Calendar.MONTH)
                val endDay = endCalendar.get(Calendar.DAY_OF_MONTH)
                applyEntity.startTime=""+startMonth+"月"+starDay+"日"
                applyEntity.endTime=""+endMonth+"月"+endDay+"日"
            }catch (e : Exception){

            }
        }
        applyAdapter.setNewInstance(allApply)
        var list : ArrayList<ApplyEntity>
        applyAdapter.setOnItemClickListener { adapter, view, position ->
            list= adapter.data as ArrayList<ApplyEntity>
            when(list[position].allapply.toString()){
                "来访" ->{
                    ARouter.getInstance().build("/apply/DetailActivity")
                        .withSerializable("visitor",list[position])
                        .withString("where","来访")
                        .navigation()
                }
                "车位" ->{
                    ARouter.getInstance().build("/apply/DetailActivity")
                        .withSerializable("visitor",list[position])
                        .withString("where","车位")
                        .navigation()
                }
                "报修" ->{
                    LogUtils.e("====报修")
                }
            }
        }
        for (applyEntity in allApply) {
            when(applyEntity.type){
                0L ->{
                    applyEntity.allapply="来访"
                }
                1L ->{
                    applyEntity.allapply="车位"
                }
                2L ->{
                    applyEntity.allapply="报修"
                }
            }
            when(applyEntity.state){
                0L ->{
                    applyEntity.aplystatues="已通过"
                }
                1L ->{
                    applyEntity.aplystatues="待审批"
                }
                2L ->{
                    applyEntity.aplystatues="未通过"
                }
            }
        }
    }
    private  var allSearch : ArrayList<ApplyEntity> =ArrayList()
    private fun search() {
        var flag=false
        v.viewRelative.setOnClickListener {
            val inflate = LayoutInflater.from(this).inflate(R.layout.item_search, null, false)
            var statues = "全部"
            inflate.findViewById<RadioGroup>(R.id.rg_statues).setOnCheckedChangeListener(object : RadioGroup.OnCheckedChangeListener{
                override fun onCheckedChanged(p0: RadioGroup?, p1: Int) {
                    when(p1){
                        R.id.rb_statues ->statues="全部"
                        R.id.rb_sub ->statues="待提交"
                        R.id.rb_verify ->statues="待审核"
                        R.id.rb_pass ->statues="已通过"
                        R.id.rb_refuse ->statues="已驳回"
                        R.id.rb_ing ->statues="审核中"
                    }
                }
            })
            var apply ="全部申请"
            inflate.findViewById<RadioGroup>(R.id.rg_apply).setOnCheckedChangeListener(object : RadioGroup.OnCheckedChangeListener{
                override fun onCheckedChanged(p0: RadioGroup?, p1: Int) {
                    when(p1){
                        R.id.rb_apply ->apply="全部申请"
                        R.id.rb_parking ->apply="车位"
                        R.id.rb_fix ->apply="维修"
                    }
                }
            })
            val popupWindow =PopupWindow()
            popupWindow.height=1000
            popupWindow.width=LinearLayout.LayoutParams.MATCH_PARENT
            popupWindow.contentView=inflate
            popupWindow.isFocusable=true
            popupWindow.showAsDropDown(v.viewRelative)
            inflate.findViewById<TextView>(R.id.sure_search).setOnClickListener {
                popupWindow.dismiss()
                if (apply=="全部申请"&&statues=="全部"){
                    applyAdapter.setNewInstance(allApply)
                    return@setOnClickListener
                }
                var oneFlag = false
                allSearch.clear()
                if (statues=="全部"){
                    for (applyEntity in allApply) {
                        if (apply==applyEntity.allapply){
                            allSearch.add(applyEntity)
                            oneFlag=true
                        }
                    }
                    if (oneFlag){
                      applyAdapter.setNewInstance(allSearch)
                    }
                    return@setOnClickListener
                }
                for (applyEntity in allApply) {
                    if (apply==applyEntity.allapply&&statues==applyEntity.aplystatues){
                        allSearch.add(applyEntity)
                        flag=true
                    }
                }
                if (flag){
                    applyAdapter.setNewInstance(allSearch)
                }else{
                    ToastUtils.showShort("没有数据")
                }
            }
            inflate.findViewById<TextView>(R.id.reset_search).setOnClickListener {

            }

        }
        v.applyTime.setOnClickListener {
            val ca = Calendar.getInstance()
            val mYear = ca[Calendar.YEAR]
            val mMonth = ca[Calendar.MONTH]
            val mDay = ca[Calendar.DAY_OF_MONTH]
            val pvDate = DatePickerDialog(this,DatePickerDialog.OnDateSetListener{
                view,year,month,dayOfMonth ->
                dateSearch(year,month+1,dayOfMonth)
            },mYear,mMonth,mDay)
            pvDate.show()

        }
    }
    private fun dateSearch(year: Int, i: Int, dayOfMonth: Int) {
        val  startCalendar= Calendar.getInstance()
        val  endCalendar= Calendar.getInstance()
        val dateSearch : ArrayList<ApplyEntity> =ArrayList()
        var flag =false
        for (applyEntity in allApply) {
            try {
                val applyTime = applyEntity.applyTime!!.toLong()
                startCalendar.timeInMillis=applyTime
                endCalendar.timeInMillis=applyTime*1000
                val startYear = startCalendar.get(Calendar.MONTH)
                val startMonth = startCalendar.get(Calendar.MONTH)
                val starDay = startCalendar.get(Calendar.DAY_OF_MONTH)
                val endMonth = endCalendar.get(Calendar.MONTH)
                val endDay = endCalendar.get(Calendar.DAY_OF_MONTH)
                if (startYear==year&&(startMonth<=i||i<=endMonth)&&(starDay<=dayOfMonth||dayOfMonth<=endDay)){
                    dateSearch.add(applyEntity)
                    flag=true
                }
            }catch (e : Exception){

            }
        }
        LogUtils.e("====$flag")
        if (flag){
            applyAdapter.setNewInstance(dateSearch)
        }else{
            ToastUtils.showShort("没有")
        }
    }

    private fun initDate() {
        statues_txt.add("全部")
        statues_txt.add("待提交")
        statues_txt.add("待审核")
        statues_txt.add("已通过")
        statues_txt.add("已驳回")
        statues_txt.add("审核中")
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {

    }

    override fun onDateChanged(p0: DatePicker?, p1: Int, p2: Int, p3: Int) {
    }

}

